package com.wiringweb.parameterprocessor.implementation;

import com.gooddies.utils.AnyToAnyConverter;
import com.wiringweb.exceptions.WiringWebException;
import com.wiringweb.parameterprocessor.ParameterProcessorInterface;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Dmitry
 */
public class PathVariableImpl extends ParameterProcessorInterface {
    private Class parameterType;

    public PathVariableImpl(Class parameterType) {
        this.parameterType = parameterType;
    }

    public PathVariableImpl() {
    }

    @Override
    public Object process(HttpServletResponse response, HttpServletRequest request, String[] urlParameter, int parameterIndex) {
        if (parameterIndex >= urlParameter.length) {
            return null;
        }
        String parameter = urlParameter[parameterIndex];
        try {
            String decodedParameter = URLDecoder.decode(parameter, "UTF-8");
            return AnyToAnyConverter.convert(String.class, parameterType, decodedParameter);
        } catch (UnsupportedEncodingException ex) {
            throw new WiringWebException("Cannot process url parameter " + parameter);
        }
    }

    @Override
    public int getProcessedGroupCount() {
        return 1;
    }

    @Override
    public ParameterProcessorInterface construct(Class argumentType, Annotation annotation) {
        return new PathVariableImpl(argumentType);
    }

}
